package cn.com.servletcontext;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

@WebServlet(name = "sContext04", value = "/sContext04")
public class sContext04 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletContext context=this.getServletContext();
        PrintWriter out=response.getWriter();
        //获取相对路径中的流入对象
        //InputStream in=context.getResourceAsStream("/WEB-INF/classes/dbcpconfig.properties");


        //获取文件的绝对路径
//        String path=context.getRealPath("/WEB-INF/classes/dbcpconfig.properties");
//        //新建文件字节输入流对象
//        FileInputStream in=new FileInputStream(path);

        //通过类的加载器找到文件路径，读取配置文件
        InputStream in=new sContext04().getClass().getClassLoader().getResourceAsStream("dbcpconfig.properties");

        //新建一个配置文件对象
        Properties pros = new Properties();
        //把文件以输入流的形式加载到配置对象中
        pros.load(in);
        out.println("username=" + pros.getProperty("username") +"<br/>");
        out.println("password=" + pros.getProperty("password") +"<br/>");

        // 循环打印所有属性
        Set<String> propertyNames = pros.stringPropertyNames();
        for (String name : propertyNames) {
            out.println(name + "=" + pros.getProperty(name) + "<br/>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}